package com.java.simple.study.juc.pattern;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhoujunlin
 * @date 2022年04月05日 20:14
 * @desc
 */
@Slf4j(topic = "c.TestTwoPhaseTermination")
public class TestTwoPhaseTermination {

    public static void main(String[] args) {
        //TPTInterrupt t = new TPTInterrupt();
        TPTVolatile t = new TPTVolatile();
        t.start();

        Sleeper.sleep(5);
        log.debug("stop");
        t.stop();
    }

}

@Slf4j(topic = "c.TPTInterrupt")
class TPTInterrupt {
    private Thread thread;

    public void start() {
        thread = new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            while (true) {
                if (currentThread.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    // sleep被打断 进入catch块
                    Thread.sleep(1000);
                    // 这里被打断的话  不会catch块 进入下次循环判断是否被打断
                    log.debug("将监控结果保存");
                } catch (InterruptedException e) {
                    // 由于sleep时线程被打断 会清除打断标记  所以这里需要手动再打断
                    currentThread.interrupt();
                }
            }
        }, "监控线程");
        thread.start();
    }

    public void stop() {
        thread.interrupt();
    }
}

@Slf4j(topic = "c.TPTVolatile")
class TPTVolatile {

    private Thread thread;
    private volatile boolean stop = false;

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                if (stop) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    // sleep被打断 进入catch块
                    Thread.sleep(1000);
                    // 这里被打断的话  不会catch块 进入下次循环判断是否被打断
                    log.debug("将监控结果保存");
                } catch (InterruptedException e) {
                }
            }
        }, "监控线程");
        thread.start();
    }

    public void stop() {
        stop = true;
        thread.interrupt();
    }
}
